<?php
class LoginController extends BaseController{
    private $errors;
    private $login = false;

    public function index(){
       
        if(!empty($_SESSION)){
            ErrorHandler::setException('MultiEnter', __LINE__, __FILE__);   
            exit;
        } else {
            $this->valid();
        }
    }

    public function logout(){
        $curuser = UserMapper::getCurrentUser();
        if('' != $curuser->getId()){
            session_start();
            unset($_SESSION['id']);
            session_destroy();
            header('Location: /WadOS/index');
        }
    }
    public function valid(){
        $err = '';
        $error='';
        $username='';
        $password='';
        $users = new UserModel();

        $arr = $users->fetchAllLittleUsers();
        if(isset($_POST)){
            $eh = ErrorHandler::getInstance();

            if(!empty($_POST['username'])){
                $username = $_POST['username'];
            } else {
                $error = $eh->setException('failUsername', __LINE__, __FILE__);
            }

            if(!empty($_POST['password'])){
                $password = $_POST['password'];
            } else {
                $error = $eh->setException('failPassword', __LINE__, __FILE__);
            }
            
            $user = $users->isUser($username);
            if($user != false){
                $users->find($user[0]['id']);
                if(md5($users->getSalt() . $password) === $users->getPassword()){
                    $_SESSION['id'] = $users->getId();
                    UserMapper::getCurrentUser();
                    header('Location: /WadOs/index/index');
                }else{
                    $error = $eh->setException('failCheckPassword', __LINE__, __FILE__);
                }
            }else{
                $error = $eh->setException('failFindUser', __LINE__, __FILE__);
            }
        }
       
        $temp = Template::getInstance();
        $temp->set('errors', $error, true);
        $temp->show('header');
        $temp->show('firstpage');
        $temp->show('footer');
    }

}
?>
